'use client';

import { useState, useEffect } from 'react';
import { 
  Box, 
  Container, 
  Typography, 
  Grid, 
  Card, 
  CardContent,
  CardActions,
  Button,
  Chip,
  TextField,
  InputAdornment,
  CircularProgress,
  Pagination,
  Divider,
  Alert
} from '@mui/material';
import Navbar from '@/components/Navbar';
import SearchIcon from '@mui/icons-material/Search';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import axios from 'axios';
import api from '@/utils/api';

// 分类列表
const categories = [
  '全部',
  '融资支持',
  '税收优惠',
  '产业发展',
  '创新创业',
  '人才支持',
  '技术改造',
  '其他政策'
];

interface Policy {
  id: number;
  title: string;
  summary: string;
  source: string;
  publishDate: string | null;
  url: string;
  category: string;
  tags: string[];
}

export default function EnterprisePoliciesPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  const [policies, setPolicies] = useState<Policy[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('全部');
  const [page, setPage] = useState<number>(1);
  const [totalPages, setTotalPages] = useState<number>(1);
  const [error, setError] = useState<string>('');

  // 从URL参数初始化状态
  useEffect(() => {
    const pageParam = searchParams.get('page');
    const categoryParam = searchParams.get('category');
    const searchParam = searchParams.get('search');
    
    if (pageParam) {
      setPage(parseInt(pageParam));
    }
    
    if (categoryParam) {
      setSelectedCategory(categoryParam);
    }
    
    if (searchParam) {
      setSearchTerm(searchParam);
    }
  }, [searchParams]);

  // 获取政策数据
  useEffect(() => {
    const fetchPolicies = async () => {
      try {
        setLoading(true);
        const response = await api.get('/api/enterprise/policies', {
          params: {
            page,
            limit: 9,
            category: selectedCategory !== '全部' ? selectedCategory : undefined,
            search: searchTerm || undefined
          }
        });
        
        if (response.data.success) {
          setPolicies(response.data.policies);
          setTotalPages(response.data.totalPages);
        } else {
          setError(response.data.message || '获取政策数据失败');
        }
        
        setLoading(false);
      } catch (err) {
        console.error('获取政策数据失败:', err);
        setError('获取政策数据失败，请稍后再试');
        setLoading(false);
      }
    };

    fetchPolicies();
  }, [page, selectedCategory, searchTerm]);

  // 更新URL参数
  useEffect(() => {
    const params = new URLSearchParams();
    
    if (page > 1) {
      params.set('page', page.toString());
    }
    
    if (selectedCategory !== '全部') {
      params.set('category', selectedCategory);
    }
    
    if (searchTerm) {
      params.set('search', searchTerm);
    }
    
    const queryString = params.toString();
    const url = queryString ? `/enterprise/policies?${queryString}` : '/enterprise/policies';
    
    // 使用replace避免在历史记录中创建过多条目
    window.history.replaceState({}, '', url);
  }, [page, selectedCategory, searchTerm]);

  // 处理搜索
  const handleSearch = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      setPage(1);
      setSearchTerm((event.target as HTMLInputElement).value);
    }
  };

  // 处理分类筛选
  const handleCategoryChange = (category: string) => {
    setSelectedCategory(category);
    setPage(1);
  };

  // 处理分页
  const handlePageChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setPage(value);
  };

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        {/* 错误提示 */}
        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}
        
        {/* 分类筛选 */}
        <Box sx={{ mb: 4, display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {categories.map((category) => (
            <Chip
              key={category}
              label={category}
              onClick={() => handleCategoryChange(category)}
              color={selectedCategory === category ? 'primary' : 'default'}
              variant={selectedCategory === category ? 'filled' : 'outlined'}
              sx={{ mb: 1 }}
            />
          ))}
        </Box>
        
        {/* 政策列表 */}
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
            <CircularProgress />
          </Box>
        ) : policies.length > 0 ? (
          <Grid container spacing={3}>
            {policies.map((policy) => (
              <Grid item xs={12} md={6} lg={4} key={policy.id}>
                <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                  <CardContent sx={{ flexGrow: 1 }}>
                    <Typography variant="h6" gutterBottom noWrap sx={{ fontWeight: 'bold' }}>
                      {policy.title}
                    </Typography>
                    <Box sx={{ display: 'flex', gap: 1, mb: 2, flexWrap: 'wrap' }}>
                      <Chip size="small" label={policy.category} color="primary" />
                      {policy.tags.slice(0, 2).map((tag, index) => (
                        <Chip key={index} size="small" label={tag} variant="outlined" />
                      ))}
                    </Box>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                      发布单位: {policy.source} | 发布日期: {policy.publishDate || '未知'}
                    </Typography>
                    <Divider sx={{ my: 1 }} />
                    <Typography variant="body2" color="text.secondary" sx={{ 
                      height: 80, 
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 3,
                      WebkitBoxOrient: 'vertical'
                    }}>
                      {policy.summary}
                    </Typography>
                  </CardContent>
                  <CardActions>
                    <Button 
                      size="small" 
                      component={Link}
                      href={`/enterprise/policies/${policy.id}`}
                    >
                      查看详情
                    </Button>
                    <Button 
                      size="small"
                      color="secondary"
                      component="a"
                      href={policy.url}
                      target="_blank"
                      rel="noopener"
                    >
                      原文链接
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
        ) : (
          <Box sx={{ textAlign: 'center', py: 6 }}>
            <Typography variant="h6" color="text.secondary">
              未找到符合条件的政策
            </Typography>
          </Box>
        )}
        
        {/* 分页 */}
        {totalPages > 1 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
            <Pagination 
              count={totalPages} 
              page={page} 
              onChange={handlePageChange} 
              color="primary" 
            />
          </Box>
        )}
      </Container>
    </Box>
  );
} 